<?php

namespace app\marketing\controller;

use app\common\controller\Adminbase;
use app\model\Goods;
use app\model\GoodsCategory;
use app\model\GoodsColumn as GoodsColumnModel;
use app\model\GoodsColumnGoods;
use app\model\GoodsType;

class Partners extends Adminbase
{

    public function index()
    {
        $model = 'Goods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = Goods::where($map)
                ->where('is_partners_subsidy', 1)
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_push', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_shop', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->field('*')
                ->page($page, $pageSize)
                ->order('sort asc, id desc')
                ->where('status', 1)
                ->with(['category', 'type'])
                ->select();
            $total  = Goods::where($map)->where('status', 1)->where('is_partners_subsidy', 1)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setDelAllBtn(false)
            ->setAddBtn(false)
            ->setSelfBtn([
                ['title' => '创建补贴', 'url' => url('form'), 'class' => 'layui-btn-normal']
            ])
            ->setDataUrl()
            ->setFormUrl('form')
            ->setDelUrl()
            ->addSearchItem('title', 'text', '商品标题')
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox()
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', '商品ID', null, null, true)
            ->addTableColumn('title', '标题', 550)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('sale_price', '销售价格', 120)
            ->addTableColumn('commission', '佣金', 120)
            ->addTableColumn('partners_subsidy_push', '团长推客补贴', 120)
            ->addTableColumn('partners_subsidy_shop', '团长小店补贴', 120)
            ->addTableOperation()
            ->returnForm();

        $this->assign('text', '额外提高佣金，用来增加团长的收入，金额由推客平台自己承担');
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function form()
    {
        $id = $this->request->param('id/d');
        if ($id) {
            $model = 'Goods';
            $info  = Goods::field('id, partners_subsidy_push, partners_subsidy_shop')
                ->withAttr('partners_subsidy_push', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_shop', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->get($id);
            $this->assign('id', $id);
            $this->assign('action', 2);

            if ($this->request->isPost()) {
                $data = $this->request->post();
                Goods::where('id', $id)->update([
                    'partners_subsidy_push' => intval($data['partners_subsidy_push'] * 100),
                    'partners_subsidy_shop' => intval($data['partners_subsidy_shop'] * 100),
                ]);
                return json(['code' => 0, 'msg' => '修改成功']);
            }

            $builder = new \app\common\controller\FormBuilder();
            $builder
                ->setUrl('form')
                ->setModel($model)
                ->setSuccessUrl()
                ->addFormItem('partners_subsidy_push', 'price', '团长推客补贴', '', [], 1)
                ->addFormItem('partners_subsidy_shop', 'price', '团长小店补贴', '', [], 1)
                ->setFormData($info)
                ->returnForm();
            $this->assign('module', 'app');
            $this->assign('is_verify', 0);
            return $this->fetch('admin@common/form');
        }
        if ($this->request->isPost()) {
            $data = $this->request->post('goods');
            $save = [];
            foreach ($data as $key => $value) {
                if ($value['price'] || $value['shop_price']) {
                    $save[] = [
                        'id'                    => intval($key),
                        'partners_subsidy_push' => !empty($value['price']) ? intval($value['price'] * 100) : 0,
                        'partners_subsidy_shop' => !empty($value['shop_price']) ? intval($value['shop_price'] * 100) : 0,
                        'is_partners_subsidy'   => 1,
                    ];
                }
            }
            if ($save) {
                (new Goods())->saveAll($save);
            }
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['url' => url('index')]]);
        }
        return $this->fetch('partners/form');
    }

    public function delete()
    {
        $id = $this->request->param('id/d');
        Goods::where('id', $id)->update([
            'is_partners_subsidy'   => 0,
            'partners_subsidy_push' => 0,
            'partners_subsidy_shop' => 0,
        ]);
        return json(['code' => 0, 'msg' => '删除成功']);
    }

    public function select()
    {
        $column_id = $this->request->param('column_id/d');
        $model     = 'Goods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = Goods::where($map)
                ->withAttr('source', function ($value, $data) {
                    $text = [1 => "<span class='layui-badge layui-bg-blue'>定向</span>", 2 => "<span class='layui-badge layui-bg-orange'>公开</span>"];
                    return $value ? $text[$value] : '';
                })
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('share_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_push', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('plan_type', function ($value) {
                    $text = [1 => '定向计划', 2 => '公开计划', 3 => '机构定向计划', 4 => '机构普通计划'];
                    return $text[$value] ?? '';
                })
                ->field('*')
                ->page($page, $pageSize)
                ->order('sort asc, id desc')
                ->where('status', 1)
                ->with(['category', 'type'])
                ->select();
            $total  = Goods::where($map)->where('status', 1)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        $category_list = GoodsCategory::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $category      = [];
        foreach ($category_list as $value) {
            if (!key_exists($value['id'], $category))
                $category[$value['id']] = $value['name'];
        }

        $type_list = GoodsType::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $type      = [];
        foreach ($type_list as $value) {
            if (!key_exists($value['id'], $type))
                $type[$value['id']] = $value['name'];
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setSelectDataConfirmBtn([
                ['title' => '导入', 'url' => url('import', ['column_id' => $column_id]), 'class' => 'layui-btn-normal', 'msg' => '是否导入选中商品？'],
            ])
            ->setDataUrl('select')
            ->setFormUrl('import')
            ->addSearchItem('title', 'text', '商品标题')
            ->addSearchItem('product_id', 'text', '商品ID')
            ->addSearchItem('shop_appid', 'text', '小店ID')
            ->addSearchItem('category_id', 'select', '商品分类', $category)
            ->addSearchItem('type', 'select', '商品专区', $type)
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox('left')
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('source', '来源', 120)
            ->addTableColumn('plan_type', '计划类型销售价格', 130)
            ->addTableColumn('product_id', '商品ID', 180)
            ->addTableColumn('title', '标题', 550)
            ->addTableColumn('sale_price', '销售价格', 150)
            ->addTableColumn('commission', '佣金', 150)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('category_name', '商品分类', 120)
            ->addTableColumn('type_name', '商品专区', 120)
            ->addTableColumn('stock_num', '库存', 120)
            ->addTableColumn('partners_subsidy_push', '团长推客补贴', 150)
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function import()
    {
        $ids = $this->request->param('ids');
        return json(['code' => 0, 'msg' => '导入成功', 'data' => ['parent' => 1, 'ids' => $ids]]);
    }

    public function get_goods()
    {
        $ids   = $this->request->param('ids');
        $goods = Goods::where('id', 'in', $ids)
            ->field('id, title, image, sale_price, commission')
            ->withAttr('sale_price', function ($value) {
                return $value > 0 ? number_format($value / 100, 2) : 0;
            })
            ->withAttr('commission', function ($value) {
                return $value > 0 ? number_format($value / 100, 2) : 0;
            })
            ->select()->toArray();
        if (empty($goods)) {
            return json(['code' => -1, 'msg' => '没有查询到商品信息']);
        }
        return json(['code' => 0, 'msg' => 'success', 'data' => $goods]);
    }

}
